/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.nc.kyiv.yellow.sociallibrary.books;

import com.nc.kyiv.yellow.sociallibrary.dao.BookDAO;
import com.nc.kyiv.yellow.sociallibrary.helper.MapBuilder;
import com.nc.kyiv.yellow.sociallibrary.similarUse.CommonClassesInterface;
import java.util.Map;

/**
 *
 * @author Evgeniy Grigorevskiy
 */
public class AddToLocalLibrary implements CommonClassesInterface {

    String userID;

    public AddToLocalLibrary() {
    }

    public AddToLocalLibrary(String userID) {
        this.userID = userID;
    }

    @Override
    public String execute(String parameters) throws Exception {
        String[] mapKeys = {"isbn"};
        MapBuilder helper = new MapBuilder();
        Map bookInfo = helper.stringToMap(parameters, mapKeys, helper.getRequestSplitter());
        if (bookInfo != null && !userID.equals("guest")) {
            long correctISBN;
            try {
                switch (bookInfo.get("isbn").toString().length()) {
                    case 10:
                        correctISBN = Long.parseLong(bookInfo.get("isbn").toString());
                        break;
                    case 13:
                        correctISBN = Long.parseLong(bookInfo.get("isbn").toString());
                        break;
                    case 14:
                        String newIsbn = bookInfo.get("isbn").toString().replace("-", "");
                        correctISBN = Long.parseLong(newIsbn);
                        break;
                    default:
                        return "failed";
                }
                bookInfo.put("isbn", correctISBN);
                bookInfo.put("userId", userID);
            } catch (Exception ex) {
                return "failed";
            }
            
            BookDAO dao = new BookDAO();
            try{
                dao.addToLocalLibrary(bookInfo);
            } catch (Exception ex){
                System.out.println("Another one book");
                return "Book is already exist in your local library";
            }
            return "success";
        }
        return "failed";
    }
}
